package com.wxq.day0416.controller;

import com.wxq.day0416.pojo.Person;
import com.wxq.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author wxq
 * @Date 2021/4/16
 **/
@Controller
public class TestController {

    /**
     * 接收页面请求的JSON数据，并返回JSON格式结果
     */
    @RequestMapping(value = "/testJson")
    @ResponseBody
    public Person testJson(@RequestBody Person user, HttpServletRequest request) {
        //打印接受到的JSON格式数据
        System.out.println("username = " + user.getUsername());
        System.out.println("password = " + user.getPassword());
//        System.out.println("age = " + user.getAge());
        return user;
    }

    @RequestMapping("/gotoTest")
    public String gotoTest() {
        System.out.println("正在测试拦截器，InterceptorController 的 gotoTest()方法正在执行！");
        return "test";
    }

    @RequestMapping("/login")
    public String userLogin(HttpServletRequest request, Model model, User user) {
        try {
            if (user.getUname().equals("admin") && user.getUpwd().equals("123456")) {
                request.getSession().setAttribute("user", user);
                return "forward:main";
            }
        } catch (Exception e) {
            return "redirect:/login.jsp";
        }
        //用户名或者密码错误
        return "redirect:/login.jsp";


    }

    @RequestMapping("/main")
    public String userMain() {
        return "main";
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //清除Session
        session.invalidate();
        return "redirect:/login.jsp";
    }
}
